from .judger import get_judger,Judger
from datetime import datetime
from .models import Submission,STATUS_CHOICES,TYPE_CHOICES
from typing import List
from asyncio import Queue,create_task,CancelledError

q=Queue()
async def add_task(rid):
    global q
    await q.put(rid)

async def set_fail(rid):
    tsk=await Submission.objects.aget(id=rid)
    tsk.status="SE"
    await tsk.asave()

async def task_mainloop():
    print("Task mgr launched")
    global q
    while True:
        try:
            rid=await q.get()
        except CancelledError:
            print("Quiting task mgr")
            break
        tsk=await Submission.objects.aget(id=rid)
        try:
            j=get_judger(tsk.type)
        except:
            print("Task",rid,"Failed")
            await set_fail(rid)
            q.task_done()
            continue
        try:
            await j.submit(rid)
        except:
            pass
        q.task_done()
import os
if not os.environ.get("IN_MANAGE_PY"):
    create_task(task_mainloop())